/**
 * WechatBot
 *  - https://github.com/gengchen528/wechatBot
 */
const { WechatyBuilder } = require("wechaty");
const { FileBox } = require("file-box");
const { setSchedule } = require("./schedule/index");
const config = require("./config/index");
const untils = require("./utils/index");
const superagent = require("./superagent/index");
const WebSocket = require("ws");
const dayjs = require("dayjs");
const { downImage } = require("./utils/index");
let axios = require("axios");
const path = require("path");
// 延时函数，防止检测出类似机器人行为操作
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const instance = axios.create({
  headers: {
    "User-Agent":
      "Mozilla/5.0 (Linux; Android 13; 2211133C Build/TKQ1.220905.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/112.0.5615.135 Mobile Safari/537.36 uni-app Html5Plus/1.0 (Immersed/37.81818)",
    "Content-Type": "application/json",
    Connection: "Keep-Alive",
  },
});
let blackWordArr = ["111"];
let globalChoseMap = {};
let globalChoseArr = [561, 589];
let restartCount = 0; //重启次数
let lastMessage = '' //上一次消息
// 二维码生成
function onScan(qrcode, status) {
  require("qrcode-terminal").generate(qrcode); // 在console端显示二维码
  const qrcodeImageUrl = [
    "https://api.qrserver.com/v1/create-qr-code/?data=",
    encodeURIComponent(qrcode),
  ].join("");

  console.log(qrcodeImageUrl);
}

// 登录
async function onLogin(user) {
  console.log(`贴心小助理${user}登录了`);
  const date = new Date();
  console.log(`当前容器时间:${date}`);
  if (config.AUTOREPLY) {
    console.log(`已开启机器人自动聊天模式`);
  }
  getChoseArr();
  startWS();
}

// 登出
function onLogout(user) {
  console.log(`小助手${user} 已经登出`);
}

// 监听对话
async function onMessage(msg) {
  const contact = msg.talker(); // 发消息人
  const content = msg.text().trim(); // 消息内容
  const room = msg.room(); // 是否是群消息
  const alias = (await contact.alias()) || (await contact.name()); // 发消息人备注
  const isText = msg.type() === bot.Message.Type.Text;
  if (msg.self()) {
    return;
  }

  if (room && isText) {
    // 如果是群消息 目前只处理文字消息
    const topic = await room.topic();
    console.log(
      `群名: ${topic} 发消息人: ${await contact.name()} 内容: ${content}`
    );
  }
}

const processMessage = async (info) => {
  const { mb, timestamp, msg } = info;
  let msgData = JSON.parse(msg);
  const msgReg = new RegExp(blackWordArr.join("|"));
  if (!globalChoseArr.includes(mb)) return;
  const roomList = await bot.Room.find({ topic: "学习交流" });
  if (msgData.length > 0) {
    msgData.forEach((msgItem) => {
      if (msgItem.type === "pic") {
        downImage(msgItem.url, "images", function (fileName) {
          const filePath = path.join("./images", fileName);
          const file = FileBox.fromFile(filePath);
          roomList.say(file);
        });
      } else if (msgItem.type === "text") {
        if (msgReg.test(msgItem.msg) || msgItem.msg.length < 5) {
          //跳过关键词以及无意义消息
          return;
        }
        const data = {
          name: globalChoseMap[mb],
          msg: msgItem.msg,
          time: dayjs(Number(timestamp + "000")).format("YYYY-MM-DD HH:mm:ss"),
        };
        // 时间：${data.time}
        let msg = `
        来源：${data.name}
        消息：${msgItem.msg}
        `;
        roomList.say(msg);
      } else if (msgItem.type === "file") {
        const data = {
          name: globalChoseMap[mb],
          msg: "下载地址" + msgItem.url,
          time: dayjs(Number(timestamp + "000")).format("YYYY-MM-DD HH:mm:ss"),
        };
        let msg = `
        来源：${data.name}
        消息：${msgItem.msg}
        `;
        roomList.say(msg);
      }
    });
  }
};
// 连接到websocket
const startWS = () => {
  const client = new WebSocket("ws://120.27.239.10:8020");
  client.on("open", () => {
    console.log("WebSocket connected");
    setInterval(sendHeartBeat, 5000);
  });
  client.on("message", function (message) {
    if (message.toString() === "pong") {
      console.log("心跳保持中");
    } else {
      let newMsg = JSON.parse(message.toString());
      console.log("Received message:", newMsg);
      if(lastMessage?.msg!==newMsg.msg){ //过滤重复消息
        processMessage(newMsg);
      }
      lastMessage = newMsg
    }
  });
  client.on("close", function () {
    console.log("WebSocket disconnected");
    reconnect();
  });
  client.on("error", (error) => {
    console.error("WebSocket error:", error);
    reconnect();
  });

  function reconnect() {
    console.log(`Reconnecting...`);
    setTimeout(() => {
      restartCount++;
      console.log(`重启次数：${restartCount}`);
      if (restartCount > 5) {
        console.log("重启次数达到最大值，服务结束");
        return;
      }
      startWS();
    }, 3000); // 设置重连时间间隔，单位为毫秒
  }
  function sendHeartBeat() {
    if (client.readyState === WebSocket.OPEN) {
      client.send("ping");
    }
  }
};
const getChoseArr = async () => {
  let result = await instance.get(
    "http://120.27.239.10:1337/api/stocks?pagination[page]=1&pagination[pageSize]=200"
  );
  let totalData = [];
  const { pageCount } = result?.data.meta?.pagination;
  if (pageCount) {
    for (let i = 0; i < Number(pageCount); i++) {
      let data = await instance.get(
        `http://120.27.239.10:1337/api/stocks?pagination[page]=${i+1}&pagination[pageSize]=200`
      );
      totalData = [...totalData,...data.data.data];
    }
    if (totalData && totalData.length > 0) {
      let idArr = totalData
        .filter((item) => item.status === "enable")
        .map((item) => item.stockId);
      let idMap = {};
      totalData.forEach((item) => {
        idMap[item.stockId] = item.name;
      });
      globalChoseArr = idArr;
      globalChoseMap = idMap;
    }
  }
};
getChoseArr();
//开启定时获取
const startMonitor = async () => {
  await getChoseArr();
};
setSchedule("0 */1 * * * ?", function () {
  startMonitor();
});
// {
//   name: "WechatEveryDay",
//   puppet: "wechaty-puppet-wechat4u", // 如果有token，记得更换对应的puppet
// }
const bot = WechatyBuilder.build();

bot.on("scan", onScan);
bot.on("login", onLogin);
bot.on("logout", onLogout);
bot.on("message", onMessage);

bot
  .start()
  .then(() => console.log("开始登陆微信"))
  .catch((e) => console.error(e));
